package com.drojian.demo4.communication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.drojian.demo.R;

public class HandlerActivity extends AppCompatActivity {
    private TextView textView;
    private final Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0){
                StringBuffer data = (StringBuffer) msg.obj;
                textView.setText(data);
                Toast.makeText(HandlerActivity.this,"子线程执行完成",Toast.LENGTH_SHORT).show();
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.part4_activity_handler);
        textView = findViewById(R.id.textView);
    }

    private StringBuffer loadData() throws InterruptedException {
        StringBuffer data = new StringBuffer();
        for (int i = 0; i < 100; i++) {
            data.append("我是第"+i+"条数据");
        }
        Thread.sleep(6000);
        return data;
    }


    public void startHandler(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                StringBuffer data = null;
                try {
                    data = loadData();
                    Message message = new Message();
                    message.what = 0;
                    message.obj = data;
                    handler.sendMessage(message);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        }).start();
        Toast.makeText(this,"主线程执行完成",Toast.LENGTH_SHORT).show();
    }
}